package com.dxy.df.core.shiro;

import com.dxy.df.constants.ConstStrings;
import com.dxy.df.modules.bean.entity.UserAccountEntity;
import com.dxy.df.utils.WebUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


public class ShiroUtils {

    private ShiroUtils() {
    }

    public static UserAccountEntity getUser() {
        return (UserAccountEntity) SecurityUtils.getSubject().getPrincipal();
    }

    public static String getUserAccount() {
        HttpServletRequest httpServletRequest = WebUtil.getHttpServletRequest();
        if(null==httpServletRequest){
            return null;
        }
        if (Objects.equals("local", System.getProperty(ConstStrings.SPRING_PROFILES_ACTIVE))) {
            String testDebugDxyUserName = httpServletRequest.getHeader(ConstStrings.TEST_DEBUG_DXYUSERNAME);
            if (null != testDebugDxyUserName && !StringUtils.isEmpty(testDebugDxyUserName)) {
                return testDebugDxyUserName;
            }
        }

        if (null != SecurityUtils.getSubject() && null != SecurityUtils.getSubject().getPrincipal()) {
            return getUser().getUserAccount();
        } else {
            return "";
        }

    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }


}
